#!/bin/bash

# CarQueue 应用打包脚本
# 使用方法: ./build.sh [debug|release|clean|install|uninstall]

set -e  # 遇到错误时退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 应用信息
APP_NAME="CarQueue"
PACKAGE_NAME="com.newhope.carqueue"
DEBUG_PACKAGE_NAME="com.newhope.carqueue.debug"

# 根据实际情况修改 UniApp ID
UNIAPP_ID="__UNI__D8F70A7"

# 设备信息（如果需要指定设备）
DEVICE_ID="172.18.1.183:39833"

# HBuilderX 项目路径（需要根据实际情况修改）
HBUILDERX_PROJECT_PATH="../your-hbuilderx-project"

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否有设备连接
check_device() {
    if command -v adb >/dev/null 2>&1; then
        if [ -n "$DEVICE_ID" ]; then
            if adb -s "$DEVICE_ID" get-state >/dev/null 2>&1; then
                print_info "设备 $DEVICE_ID 已连接"
                return 0
            else
                print_warning "指定设备 $DEVICE_ID 未连接"
                return 1
            fi
        else
            CONNECTED_DEVICES=$(adb devices | grep -v "List of devices" | grep "device$" | wc -l)
            if [ "$CONNECTED_DEVICES" -gt 0 ]; then
                print_info "检测到 $CONNECTED_DEVICES 个设备已连接"
                return 0
            else
                print_warning "未检测到连接的设备"
                return 1
            fi
        fi
    else
        print_error "ADB 未找到，请确保 Android SDK 已正确安装"
        return 1
    fi
}

# 拷贝 HBuilderX 生成的文件
copy_files() {
    print_info "拷贝 HBuilderX 生成的文件..."
    
    # 检查 HBuilderX 项目路径是否存在
    if [ ! -d "$HBUILDERX_PROJECT_PATH/unpackage/resource/app-android" ]; then
        print_warning "HBuilderX 项目路径不存在或未生成 Android 资源"
        print_warning "请设置正确的 HBUILDERX_PROJECT_PATH 变量"
        return 1
    fi
    
    # 拷贝 Java 源码
    print_info "拷贝 Java 源码文件..."
    if [ -d "$HBUILDERX_PROJECT_PATH/unpackage/resource/app-android/uniappx/app-android/src" ]; then
        cp -r "$HBUILDERX_PROJECT_PATH/unpackage/resource/app-android/uniappx/app-android/src/"* app/src/main/java/
        print_success "Java 源码拷贝完成"
    else
        print_warning "Java 源码目录不存在，跳过拷贝"
    fi
    
    # 拷贝 UniApp 资源
    print_info "拷贝 UniApp 资源文件..."
    if [ -d "$HBUILDERX_PROJECT_PATH/unpackage/resource/app-android/$UNIAPP_ID" ]; then
        # 确保目标目录存在
        mkdir -p app/src/main/assets/apps/
        cp -r "$HBUILDERX_PROJECT_PATH/unpackage/resource/app-android/$UNIAPP_ID" app/src/main/assets/apps/
        print_success "UniApp 资源拷贝完成"
    else
        print_warning "UniApp 资源目录不存在，跳过拷贝"
    fi
    
    print_success "文件拷贝完成"
}

# 清理构建
clean_build() {
    print_info "清理构建缓存..."
    ./gradlew clean
    print_success "清理完成"
}

# 构建调试版本
build_debug() {
    print_info "构建调试版本..."
    ./gradlew assembleDebug
    
    if [ -f "app/build/outputs/apk/debug/app-debug.apk" ]; then
        print_success "调试版本构建完成: app/build/outputs/apk/debug/app-debug.apk"
    elif [ -f "app/release/app-debug.apk" ]; then
        print_success "调试版本构建完成: app/release/app-debug.apk"
    else
        print_error "调试版本构建失败，未找到 APK 文件"
        exit 1
    fi
}

# 构建生产版本
build_release() {
    print_info "构建生产版本..."
    ./gradlew assembleRelease
    
    if [ -f "app/build/outputs/apk/release/app-release.apk" ]; then
        print_success "生产版本构建完成: app/build/outputs/apk/release/app-release.apk"
    elif [ -f "app/release/app-release.apk" ]; then
        print_success "生产版本构建完成: app/release/app-release.apk"
    else
        print_error "生产版本构建失败，未找到 APK 文件"
        exit 1
    fi
}

# 安装应用
install_app() {
    local build_type=$1
    
    if ! check_device; then
        print_error "无法安装应用，设备未连接"
        exit 1
    fi
    
    local apk_path=""
    local package_name=""
    
    if [ "$build_type" = "debug" ]; then
        if [ -f "app/build/outputs/apk/debug/app-debug.apk" ]; then
            apk_path="app/build/outputs/apk/debug/app-debug.apk"
        elif [ -f "app/release/app-debug.apk" ]; then
            apk_path="app/release/app-debug.apk"
        fi
        package_name="$DEBUG_PACKAGE_NAME"
    else
        if [ -f "app/build/outputs/apk/release/app-release.apk" ]; then
            apk_path="app/build/outputs/apk/release/app-release.apk"
        elif [ -f "app/release/app-release.apk" ]; then
            apk_path="app/release/app-release.apk"
        fi
        package_name="$PACKAGE_NAME"
    fi
    
    if [ -z "$apk_path" ]; then
        print_error "未找到 $build_type 版本的 APK 文件，请先构建"
        exit 1
    fi
    
    print_info "安装 $build_type 版本: $apk_path"
    
    if [ -n "$DEVICE_ID" ]; then
        adb -s "$DEVICE_ID" install -r "$apk_path"
    else
        adb install -r "$apk_path"
    fi
    
    print_success "$build_type 版本安装完成"
}

# 卸载应用
uninstall_app() {
    local build_type=$1
    
    if ! check_device; then
        print_error "无法卸载应用，设备未连接"
        exit 1
    fi
    
    local package_name=""
    if [ "$build_type" = "debug" ]; then
        package_name="$DEBUG_PACKAGE_NAME"
    else
        package_name="$PACKAGE_NAME"
    fi
    
    print_info "卸载 $build_type 版本: $package_name"
    
    if [ -n "$DEVICE_ID" ]; then
        adb -s "$DEVICE_ID" uninstall "$package_name" 2>/dev/null || print_warning "$build_type 版本未安装或卸载失败"
    else
        adb uninstall "$package_name" 2>/dev/null || print_warning "$build_type 版本未安装或卸载失败"
    fi
    
    print_success "$build_type 版本卸载完成"
}

# 启动应用
launch_app() {
    local build_type=$1
    
    if ! check_device; then
        print_error "无法启动应用，设备未连接"
        exit 1
    fi
    
    local package_name=""
    if [ "$build_type" = "debug" ]; then
        package_name="$DEBUG_PACKAGE_NAME"
    else
        package_name="$PACKAGE_NAME"
    fi
    
    print_info "启动应用: $package_name"
    
    if [ -n "$DEVICE_ID" ]; then
        adb -s "$DEVICE_ID" shell am start -n "$package_name/.SplashActivity"
    else
        adb shell am start -n "$package_name/.SplashActivity"
    fi
    
    print_success "应用启动完成"
}

# 显示帮助信息
show_help() {
    echo "CarQueue 应用打包脚本"
    echo ""
    echo "使用方法:"
    echo "  ./build.sh [命令]"
    echo ""
    echo "可用命令:"
    echo "  copy               拷贝 HBuilderX 生成的文件"
    echo "  clean              清理构建缓存"
    echo "  debug              构建调试版本"
    echo "  release            构建生产版本"
    echo "  install-debug      安装调试版本"
    echo "  install-release    安装生产版本"
    echo "  uninstall-debug    卸载调试版本"
    echo "  uninstall-release  卸载生产版本"
    echo "  launch-debug       启动调试版本"
    echo "  launch-release     启动生产版本"
    echo "  full-debug         完整流程：拷贝 -> 清理 -> 构建 -> 安装 -> 启动调试版本"
    echo "  full-release       完整流程：拷贝 -> 清理 -> 构建 -> 安装 -> 启动生产版本"
    echo "  help               显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  ./build.sh release                # 只构建生产版本"
    echo "  ./build.sh full-release          # 完整的生产版本流程"
    echo "  ./build.sh clean && ./build.sh debug  # 清理后构建调试版本"
}

# 主函数
main() {
    case "${1:-help}" in
        "copy")
            copy_files
            ;;
        "clean")
            clean_build
            ;;
        "debug")
            build_debug
            ;;
        "release")
            build_release
            ;;
        "install-debug")
            install_app "debug"
            ;;
        "install-release")
            install_app "release"
            ;;
        "uninstall-debug")
            uninstall_app "debug"
            ;;
        "uninstall-release")
            uninstall_app "release"
            ;;
        "launch-debug")
            launch_app "debug"
            ;;
        "launch-release")
            launch_app "release"
            ;;
        "full-debug")
            copy_files
            clean_build
            build_debug
            install_app "debug"
            launch_app "debug"
            ;;
        "full-release")
            copy_files
            clean_build
            build_release
            install_app "release"
            launch_app "release"
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 检查是否在项目根目录
if [ ! -f "gradlew" ]; then
    print_error "请在项目根目录运行此脚本"
    exit 1
fi

# 执行主函数
main "$@"